import { entryInfoUrl, entrySaveUrl, userInfoUrl, entryBankcardUrl, bankCardOCRUrl } from '../../../../api/individual'
import { post, get, uploadFile, initUploadFileListKey, isPdfRegexp } from '../../../../utils/index'

Page({
  data: {
    page: '',
    readonly: false,
    form: { bankCardImgList: [] },
    formError: {}
  },
  async loadData () { // 获取人员信息
    const url = this.data.page === 'entry' ? entryInfoUrl : userInfoUrl
    const { data } = await post(url)
    data.companyName = data.companyVO && data.companyVO.name
    data.bankName = data.bank && data.bank.dictValue
    if (data.bankCardImgAddress) {
      data.bankCardImgList = [{ url: data.bankCardImgAddress, name: '厦门市银行卡复印件', isImage: !isPdfRegexp.test(data.bankCardImgAddress) }]
    }
    this.setData({ form: data })
    if (!data.bank.dictValue) {
      this.loadBankcard()
    }
  },
  async loadBankcard () { // 获取银行卡类型
    const { companyId } = this.data.form
    const { data } = await get(entryBankcardUrl, { companyId })
    this.setData({
      'form.bankCode': data.dictKey || '',
      'form.bankName': data.dictValue || ''
    })
    // 自动保存公司银行类型
    const { form } = this.data
    await post(entrySaveUrl, form)
  },
  async bankCardImgRead ({ detail }) { // 银行卡附件上传
    const { file } = detail
    this.setData({ formError: {} })
    let { data } = await uploadFile(file.path)
    data = initUploadFileListKey(data)
    this.setData({ 'form.bankCardImgList': [data] })
    this.data.form.bankCardImg = data.link
    this.data.form.bankCardImgId = data.id
    this.bankCardOCR()
  },
  bankCardImgDel () { // 银行卡附件删除
    this.data.form.bankCardImg = ''
    this.data.form.bankCardImgId = ''
    this.setData({ 'form.bankCardImgList': [] })
  },
  preview ({ detail }) { // 预览
    const { index } = detail
    const file = this.data.form.bankCardImgList[index]
    if (!file || file.isImage) {
      return
    }
    wx.openDocument({ filePath: file.url })
  },
  async save () { // 保存
    const { form } = this.data
    await post(entrySaveUrl, form)
    wx.navigateBack({})
  },
  bankCardNoChange ({ detail }) { // 银行卡
    this.data.form.bankCardNo = detail
  },
  async bankCardOCR () { // 银行卡ocr
    const { form } = this.data
    const { data } = await post(bankCardOCRUrl, { path: form.bankCardImg }, {}, false)
    if (data.bankName !== form.bankName) {
      wx.showToast({ title: `请上传${form.bankName}的银行卡`, icon: 'none' })
      this.setData({ 'formError.bankName': `请上传${form.bankName}的银行卡` })
      return
    }
    this.setData({ 'form.bankCardNo': data.bankCardNo })
  },
  onLoad (options) {
    // page表示从哪个页面过来的, entry->入职； change->修改；me->我的
    const { page } = options
    const readonly = page !== 'entry'
    this.setData({ readonly, page })
    this.loadData()
  }
})